package net.bwie.realtime.jtp.dwd.log.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.jtp.dwd.log.function.AdjustIsNewProcessFunction1;
import net.bwie.realtime.jtp.dwd.log.function.AppLogSplitProcessFunction1;
import net.bwie.realtime.jtp.utils.KafkaUtil;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;


public class JtpAppLogEtlJob1 {

    public static void main(String[] args) throws  Exception{

        // 1.执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2.数据源-source
        DataStream<String> kafkaDateStream = KafkaUtil.consumerKafka(env,"topic-log");
//        kafkaDateStream.print("kafka") ;
        //3.数据转换-transformation
        DataStream<String> pageStream = processLog1(kafkaDateStream);

        //4.数据输出-sink
        KafkaUtil.producerKafka(pageStream,"dwd-traffic-page-log");

        //5.触发执行-execute
        env.execute("JtpAppLogEtlJob1");
    }

    /**
     * 1.数据清洗
     * 2.新老访客状态标记修复
     * 3.分流
     * @param stream
     * @return
     */
    private static DataStream<String> processLog1(DataStream<String> stream) {
        //1.数据清洗
        DataStream<String> jsonStream = appcleaned(stream);

        //2.新老访客状态标记修复
        DataStream<String> IsNewStream = appIsNew(jsonStream);

        //3.数据分流
        DataStream<String> splitStream = Split(IsNewStream);

        return splitStream;
    }

    private static DataStream<String> Split(DataStream<String> stream) {

        // 1.侧边流输出标记
        OutputTag<String> errorTag = new OutputTag<String>("error-log") {};
        OutputTag<String> startTag = new OutputTag<String>("start-log") {};
        OutputTag<String> displayTag = new OutputTag<String>("display-log") {};
        OutputTag<String> actionTag = new OutputTag<String>("action-log") {};

        //2.日志分流处理
        SingleOutputStreamOperator<String> pageStream = stream.process(
                new AppLogSplitProcessFunction1(errorTag, startTag, displayTag, actionTag)
        );

        //测流输出
        SideOutputDataStream<String> errorStream = pageStream.getSideOutput(errorTag);
        KafkaUtil.producerKafka(errorStream,"dwd-traffic-error-log");
        SideOutputDataStream<String> startStream = pageStream.getSideOutput(startTag);
        KafkaUtil.producerKafka(startStream,"dwd-traffic-start-log");
        SideOutputDataStream<String> displayStream = pageStream.getSideOutput(displayTag);
        KafkaUtil.producerKafka(displayStream,"dwd-traffic-display-log");
        SideOutputDataStream<String> actionStream = pageStream.getSideOutput(actionTag);
        KafkaUtil.producerKafka(actionStream,"dwd-traffic-action-log");


        return pageStream;
    }

    /**
     * 1.老访客状态标记修复
     * @param stream
     * @return
     */
    private static DataStream<String> appIsNew(DataStream<String> stream) {

        //a.按照设备id进行分组
        KeyedStream<String, String> keyedStream = stream.keyBy(new KeySelector<String, String>() {
            @Override
            public String getKey(String value) throws Exception {
                return JSON.parseObject(value).getJSONObject("common").getString("mid");
            }
        });

        //b.状态编程
        DataStream<String> isNewStream= keyedStream.process(new AdjustIsNewProcessFunction1());

        //c.返回
        return isNewStream;
    }

    /**
     * 1.数据清洗
     * @param stream
     * @return
     */
    private static DataStream<String> appcleaned(DataStream<String> stream) {
        //a.脏数据侧边流输出标记
        final OutputTag<String> dirtyTag = new OutputTag<String>("dirty-log"){};

        //b.数据清洗处理
        SingleOutputStreamOperator<String> dirtyStream = stream.process(new ProcessFunction<String, String>() {
            @Override
            public void processElement(String value, Context ctx, Collector<String> out) throws Exception {
                try {
                    //解析json数据
                    JSON.parseObject(value);
                    out.collect(value);
                }catch (Exception e){
                    ctx.output(dirtyTag,value);
                }
            }
        });

        //c.侧边流输出：脏数据
        SideOutputDataStream<String> sideOutput = dirtyStream.getSideOutput(dirtyTag);
        KafkaUtil.producerKafka(sideOutput,"dwd-traffic-dirty-log");

        return dirtyStream;
    }
}
